package com.jinken.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jinken.common.result.BaseResult;
import com.jinken.common.service.IStockService;
import com.jinken.entity.TStock;
import com.jinken.mapper.StockMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


@DubboService
public class StockServiceImpl implements IStockService {

    @Autowired
    private StockMapper stockMapper;

    @Transactional
    public BaseResult deduct(String commodityCode, int count) {
        //根据商品编码查询
        LambdaQueryWrapper<TStock> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TStock::getCommodityCode, commodityCode);

        TStock tStock = stockMapper.selectOne(lambdaQueryWrapper);

        if (Objects.isNull(tStock)) {
            return BaseResult.error("商品不存在");
        }

        if (tStock.getCount() < count) {
            return BaseResult.error("库存不足");
        }

        //扣减库存
        tStock.setCount(tStock.getCount() - count);

        //修改数据库
        int row = stockMapper.updateById(tStock);

        if (row == 1) {
            return BaseResult.success();
        }

        return BaseResult.error("服务异常");
    }
}
